<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title> New Document </title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>	</style>
 </head>
 <body>
 <!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->

  <script type="text/javascript">
    /** 
 * json格式转树状结构 
 * @param   {json}      json数据 
 * @param   {String}    id的字符串 
 * @param   {String}    父id的字符串 
 * @param   {String}    children的字符串 
 * @return  {Array}     数组 
 */  
function transData(a, idStr, pidStr, childrenStr){  
    var r = [], 
	 hash = new Object(); 
	   id = idStr, 
	  pid = pidStr, 
	  children = childrenStr,
	  i = 0, j = 0, 
	  len = a.length;
	//1数组顺序转换为“以id为属性名的对象元素”
    for(; i < len; i++){  
        hash[a[i][id]] = a[i];  
    }
	//2
    for(; j < len; j++){
        var aVal = a[j], 
		  //顺序地找到各个数组元素的父元素
		  hashVP = hash[aVal[pid]];
        if(hashVP){
            !hashVP[children] && (hashVP[children] = []); 
			
			//在父元素的子节点里面推入该数组元素		
            hashVP[children].push(aVal);  
        }else{
			//如果父元素是根元素,则r数组直接增加该数组元素
            r.push(aVal);  
        }  
    }  
    return r;  
}  
  
var jsonData = [{"id":"4","pid":"1","name":"大家电"},	
				{"id":"5","pid":"1","name":"生活电器"},	
				{"id":"1","pid":"0","name":"家用电器"},	
				{"id":"2","pid":"0","name":"服饰"},	
				{"id":"3","pid":"0","name":"化妆"},	
				{"id":"7","pid":"4","name":"空调"},	
				{"id":"8","pid":"4","name":"冰箱"},	
				{"id":"9","pid":"4","name":"洗衣机"},	
				{"id":"10","pid":"4","name":"热水器"},	
				{"id":"11","pid":"3","name":"面部护理"},	
				{"id":"12","pid":"3","name":"口腔护理"},	
				{"id":"13","pid":"2","name":"男装"},	
				{"id":"14","pid":"2","name":"女装"},	
				{"id":"15","pid":"7","name":"海尔空调"},	
				{"id":"16","pid":"7","name":"美的空调"},	
				{"id":"19","pid":"5","name":"加湿器"},	
				{"id":"20","pid":"5","name":"电熨斗"}];
  
var jsonDataTree = transData(jsonData, 'id', 'pid', 'children');  
console.log(jsonDataTree);  
//结果如下：
/*
[
	{"id":"1","pid":"0","name":"家用电器", "children":[
		{"id":"4","pid":"1","name":"大家电", "children":[
			{"id":"7","pid":"4","name":"空调", "children":[
				{"id":"15","pid":"7","name":"海尔空调"},
				{"id":"16","pid":"7","name":"美的空调"}
			]},
			{"id":"8","pid":"4","name":"冰箱"},
			{"id":"9","pid":"4","name":"洗衣机"},
			{"id":"10","pid":"4","name":"热水器"}
		]},
		{"id":"5","pid":"1","name":"生活电器","children":[
			{"id":"19","pid":"5","name":"加湿器"},
			{"id":"20","pid":"5","name":"电熨斗"}
		]}
	]},
	{"id":"2","pid":"0","name":"服饰","children":[
		{"id":"13","pid":"2","name":"男装"},
		{"id":"14","pid":"2","name":"女装"}
	]},
	{"id":"3","pid":"0","name":"化妆","children":[
		{"id":"11","pid":"3","name":"面部护理"},
		{"id":"12","pid":"3","name":"口腔护理"}
	]}
]  */
  </script>
 </body>
</html>